package org.example.volunteerend.service.impl;

import java.util.List;

import org.example.volunteerend.dto.CommentCreateRequest;
import org.example.volunteerend.dto.PageResponse;
import org.example.volunteerend.entity.CommunityComment;
import org.example.volunteerend.entity.VolunteerProject;
import org.example.volunteerend.mapper.CommunityCommentMapper;
import org.example.volunteerend.mapper.VolunteerProjectMapper;
import org.example.volunteerend.service.CommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;

@Service
public class CommunityServiceImpl implements CommunityService {

    private final CommunityCommentMapper commentMapper;
    private final VolunteerProjectMapper projectMapper;
    
    @Autowired
    public CommunityServiceImpl(CommunityCommentMapper commentMapper, VolunteerProjectMapper projectMapper) {
        this.commentMapper = commentMapper;
        this.projectMapper = projectMapper;
    }
    
    @Override
    @Transactional
    public Integer addComment(CommentCreateRequest request, Integer userId) {
        // 检查项目是否存在
        VolunteerProject project = projectMapper.findById(request.getProject_id());
        if (project == null) {
            throw new IllegalArgumentException("项目不存在");
        }
        
        // 创建评论对象
        CommunityComment comment = new CommunityComment();
        comment.setUserId(userId);
        comment.setProjectId(request.getProject_id());
        comment.setContent(request.getContent());
        comment.setRating(request.getRating());
        comment.setParentCommentId(request.getParent_comment_id());
        
        // 保存评论
        commentMapper.insert(comment);
        
        return comment.getCommentId();
    }
    
    @Override
    public PageResponse<CommunityComment> getProjectComments(
            Integer projectId, 
            Integer page, 
            Integer pageSize, 
            String sortBy, 
            String sortOrder) {
        
        // 设置默认值
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        
        // 使用PageHelper进行分页
        PageHelper.startPage(page, pageSize);
        
        // 查询一级评论
        List<CommunityComment> rootComments = commentMapper.findRootCommentsByProjectId(projectId, sortBy, sortOrder);
        
        // 查询每个一级评论的回复
        for (CommunityComment rootComment : rootComments) {
            List<CommunityComment> replies = commentMapper.findRepliesByParentId(rootComment.getCommentId());
            // 将回复添加到parentComment字段中，方便后续处理
            for (CommunityComment reply : replies) {
                reply.setParentComment(rootComment);
            }
        }
        
        // 统计总评论数
        int total = commentMapper.countCommentsByProjectId(projectId);
        
        return new PageResponse<>(rootComments, total, page, pageSize);
    }
    
    @Override
    public PageResponse<CommunityComment> getAllProjectComments(
            Integer projectId, 
            Integer page, 
            Integer pageSize, 
            String sortBy, 
            String sortOrder) {
        
        // 设置默认值
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        
        // 如果是查询所有评论，则不使用PageHelper分页，而是在控制器中手动分页
        // 这样可以获取所有评论后再处理父子关系
        if (page == null && pageSize == null) {
            List<CommunityComment> allComments = commentMapper.findAllCommentsByProjectId(projectId, sortBy, sortOrder);
            // 统计所有评论数（包括回复）
            int total = allComments.size();
            return new PageResponse<>(allComments, total, 1, total);
        }
        
        // 使用PageHelper进行分页
        PageHelper.startPage(page, pageSize);
        
        // 查询所有评论（包括回复）
        List<CommunityComment> allComments = commentMapper.findAllCommentsByProjectId(projectId, sortBy, sortOrder);
        
        // 处理父评论关系
        for (CommunityComment comment : allComments) {
            if (comment.getParentCommentId() != null) {
                // 查找父评论
                for (CommunityComment potentialParent : allComments) {
                    if (potentialParent.getCommentId().equals(comment.getParentCommentId())) {
                        comment.setParentComment(potentialParent);
                        break;
                    }
                }
            }
        }
        
        // 统计总评论数（这里应该计算所有评论的总数，包括回复）
        int total = allComments.size();
        
        return new PageResponse<>(allComments, total, page, pageSize);
    }
    
    @Override
    @Transactional
    public Integer likeProject(Integer projectId, String action) {
        // 检查项目是否存在
        VolunteerProject project = projectMapper.findById(projectId);
        if (project == null) {
            throw new IllegalArgumentException("项目不存在");
        }
        
        // 更新点赞数
        if ("like".equals(action)) {
            projectMapper.incrementLikes(projectId);
        } else if ("unlike".equals(action)) {
            projectMapper.decrementLikes(projectId);
        } else {
            throw new IllegalArgumentException("无效的操作类型");
        }
        
        // 返回更新后的点赞数
        project = projectMapper.findById(projectId);
        return project.getLikes();
    }
} 